package cn.humaohua.study.yanmo_design_pattern.ch04.v1;

import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.List;

public class LogFileOperate implements LogFileOperateApi {

    /**
     * 日志文件的路径和文件名称，默认是在项目根目录下的AdapterLog.log
     */
    private String logFilePath = "AdapterLog.log";

    public LogFileOperate(String logFilePath) {
        // 如果提供了日志文件的存储路径，则使用指定路径的文件
        if (StringUtils.isNotEmpty(logFilePath))
            this.logFilePath = logFilePath;
    }

    @Override
    public List<LogModel> readLogFile() {
        try (FileInputStream fis = new FileInputStream(logFilePath);
             ObjectInputStream ois = new ObjectInputStream(fis)) {
            List<LogModel> list = (List<LogModel>) ois.readObject();
            return list;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    public void writeLogFile(List<LogModel> list) {
        try (FileOutputStream fos = new FileOutputStream(logFilePath);
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
